/******************************************************************************
 *
 * SD products client with connect timeout only.
 *
 *****************************************************************************/
#include	"unp.h"
#include    "ajay.h"

char srv_name[100];
void cl_get(void);

int
main(int argc, char **argv)
{
	pthread_t    tid;
	void **status;

	if (argc != 2)
		err_quit("usage: a.out <IPaddress>");


	strcpy(srv_name,argv[1]);
	//printf("%s", srv_name);
	//printf("Before calling thread");
	Pthread_create(&tid, NULL,cl_get ,NULL);
	//printf("Before thread join\n");
    Pthread_join(tid, status);
    //printf("After thread join\n");
	exit(0);
}


void cl_get(void){
	int					sockfd, n;
		char				recvline[MAXLINE + 1];
		struct sockaddr_in	servaddr;
		int 				retval=-1;
		int 				i=0;
		int 				no_of_rdng=20;
		char outStr[100];

		time_t rawtime;
		struct tm *timeinfo;
		//printf ( "Current local time and date: %s", asctime (timeinfo) );

	if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
			err_sys("socket error");

		bzero(&servaddr, sizeof(servaddr));
		servaddr.sin_family = AF_INET;
		servaddr.sin_port   = htons(2000);	/* daytime server */
		//printf("inside thread\n");
		if (inet_pton(AF_INET, srv_name, &servaddr.sin_addr) <= 0)
			err_quit("inet_pton error for %s", srv_name[1]);

		//if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0) //regular connect.
		if (connect_timeo(sockfd, (SA *) &servaddr, sizeof(servaddr), 5) < 0) //timeout connect
			err_sys("connect error");

		for(i=0;i<no_of_rdng;i++){
			n = write(sockfd, T_CMD, sizeof(T_CMD));
			if(n!=sizeof(T_CMD)){
				err_sys("write error");
			}

			/* timeout on a read operation */
			retval=Readable_timeo(sockfd,10);
			if(retval==0){
				err_sys("read timeout");
			}else{
				if ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
					recvline[n] = '\n';	/* null terminate */
					time ( &rawtime );
					timeinfo = localtime ( &rawtime );
					strcpy(outStr,asctime(timeinfo));
					outStr[strlen(outStr) - 1]=NULL;
					strcat(outStr,",");
					strcat(outStr,recvline);
					if (fputs(outStr, stdout) == EOF)
						err_sys("fputs error");
				}
				if (n < 0)
					err_sys("read error");
			}
			sleep(2);
		}

		close(sockfd);
       // printf("end of thread\n");
		return;
}

